import ddddocr
from PIL import Image, ImageDraw, ImageFont
import io
import requests

from fontTools.ttLib import TTFont

# 创建ddddocr
ocr = ddddocr.DdddOcr()

# 创建字体映射表
font_maps = {

}

# 获取特殊字体
font = TTFont("./static/font/file")
for code, name in font.getBestCmap().items():
    if code == 120:
        continue
    else:
        print(code, chr(code), name)
    # 1. 创建画布
    img = Image.new("RGB", (25, 25), (255, 255,  255))
    # 2. 指定字体
    img_font = ImageFont.truetype("./static/font/file", 20)
    # 3. 绘制图片
    draw = ImageDraw.Draw(img)
    draw.text((0, 0), text=chr(code), fill=(0, 0, 0), font=img_font)
    # 4. 保存图片
    # 创建内存字节流io.BytesIO()
    img_bytes = io.BytesIO()
    # 保存图片到内存字节流img.save(img_bytes, format="JPEG"), 避免磁盘I/O，速度更快
    img.save(f'./static/font/imgs/{code}.png', "png")

    img.save(img_bytes, format="JPEG")
    # classification识别图片二进制  img_bytes.getvalue()图片字节流转图片二进制
    r = ocr.classification(img_bytes.getvalue())
    print(code, "识别结果", r)
    font_maps[chr(code)] = r

print("字体映射表")
print(font_maps)

